# -*- coding: utf-8 -*-
import common.libs.Helper
from application import app, db,mail
from common.models.interview_comment import InterviewComment
from common.libs.SQLTransform import queryToDict
from common.models.bpm import Bpm
from common.models.formation import Formation
from common.models.interview_goal import InterviewGoal
from common.libs.Helper import unduplicate
from dingtalk import SecretClient, model
from flask import Blueprint, request, make_response, redirect
from common.models.user import User
from sqlalchemy import distinct
import json, requests
from sqlalchemy import and_, or_
import urllib.parse
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from config.dingtalk_setting import AppKey,AppSecret,AgentId,role_hr
from flask_mail import Mail, Message
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.libs.Helper import dateafter
from common.libs.Helper import dingtalkpost




interview_page = Blueprint("interview_page", __name__)


##连接
client = SecretClient(AppKey, AppSecret)  # 新 access_token 获取方式


@interview_page.route('/getinterviewuser', methods=['GET', 'POST'])
def getinterviewuser():
    status = request.json.get('status')
    member = User.query.order_by(User.created_time.desc()).filter_by(status=status).all()
    rts = []
    for item in member:
        comment = InterviewComment.query.order_by(InterviewComment.created_time.desc()).filter_by(interviewid=item.id).first()
        if comment :
            username = comment.user.name
        else:
            username = "面试未开始"
        temp = dict(id=item.id, name=item.name, department=item.department.name,
                    email=item.email, sex=item.sex, idcardnum=item.idcardnum,mobile=item.mobile,interviewdate=str(item.interviewdate), post=item.post,username=username)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@interview_page.route('/setinfo', methods=['GET', 'POST'])
def setinfo():
    id = request.json.get("id")
    salary = request.json.get("salary")
    employdate = request.json.get("employdate")

    user = User.query.filter_by(id=id).first()
    user.salary = salary
    user.employdate =employdate

    db.session.commit()

    return json.dumps("成功", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@interview_page.route('/getinterviewcomment', methods=['GET', 'POST'])
def getInterviewComment():
    id = request.args.get('id')
    comment = InterviewComment.query.order_by(InterviewComment.id).filter_by(interviewid=id).all()
    rts = []
    for item in comment:
        temp = dict(name=item.user.name, comment=item.comment, score=item.score, userid=item.userid,
                    isagree=item.isagree,minsalary=item.minsalary,maxsalary=item.maxsalary,minemploydate=str(item.minemploydate),maxemploydate=str(item.maxemploydate))
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)



@interview_page.route('/sendinterview', methods=['GET', 'POST'])
def sendinterview():
    type=request.json.get("type")
    userid = request.json.get("list")
    userlist = userid.split("。")
    interviewid = str(request.json.get("id"))
    posterid = request.json.get("posterid")


    member = User.query.filter_by(id=interviewid).first()

    name = member.name
    department = member.department.name
    post = member.post

    base_url = 'http://101.132.227.54:88/interviewcard?id=' + interviewid + '&userid=' + userid + '&posterid=' + posterid + '&showsalary='+str(type)
    encodeurl = urllib.parse.quote(base_url)

    dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding976485bf6d4d1f69acaaa37764f94726&container_type=work_platform&app_id=0_1517315486&redirect_type=jump&redirect_url=" + encodeurl
    normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

    msg = {
        "msgtype": "action_card",
        "action_card": {
            "title": "面试信息",
            "markdown": "![](http://upload.guanzhuoran.cn/interview.png)   \n   #### 姓名：" + name + "  \n   #### 应聘部门：" + department + "   \n   #### 应聘岗位：" + post,
            "btn_orientation": "1",
            "btn_json_list": [
                # {
                #     "title": "查看简历(PC)",
                #     "action_url": dingtalkurl,
                # },
                {
                    "title": "查看简历",
                    "action_url": normalurl,
                },

            ]
        }
    }
    print(msg)
    a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)

    return json.dumps("简历已成功推送", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@interview_page.route('/sendinterviewfail', methods=['GET', 'POST'])
def sendinterviewfail():
    tag = request.json.get("tag")
    id = request.json.get("id")


    print(id)

    tagstr=str(tag).replace('[', '').replace(']', '').replace(' ', '').replace("'", "")
    print(tagstr)
    user=User.query.filter_by(id=id).first()
    user.tag=tagstr
    user.status=0
    db.session.commit()

    return json.dumps("已转入储备人才库", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)



@interview_page.route('/getinterviewscore', methods=['GET', 'POST'])
def getinterviewscore():
    interviewid = request.args.get("id")

    comment = InterviewComment.query.filter_by(interviewid=interviewid).all()
    commentlist = queryToDict(comment)
    sum = 0
    avg = 0
    if commentlist:
        for i in commentlist:
            sum = sum + int(i['score'])
        avg = sum / len(commentlist)
    avg = round(avg, 1)
    print(avg)
    return json.dumps(avg, ensure_ascii=False)


@interview_page.route('/postinterviewcomment', methods=['GET', 'POST'])
def postinterviewcomment():
    interviewid = request.json.get("interviewid")
    userid = request.json.get("userid")
    isagree=request.json.get("isagree")

    comment = request.json.get("comment")
    score = request.json.get("score")
    posterid = request.json.get("posterid")

    salary=request.json.get("salary")
    minsalary=request.json.get("minsalary")
    maxsalary=request.json.get("maxsalary")
    employdate = request.json.get("employdate")
    minemploydate=request.json.get("minemploydate")
    maxemploydate = request.json.get("maxemploydate")

    # posterlist = posterid.split("。")

    postinfo=User.query.filter_by(id=posterid).first()
    posteruserid=postinfo.userid
    posterlist = posteruserid.split("。")



    interviewname = request.json.get("interviewname")
    username = request.json.get("username")

    interviewcomment = InterviewComment()
    interviewcomment.interviewid = interviewid
    interviewcomment.userid = userid
    interviewcomment.comment = comment
    interviewcomment.score = score
    interviewcomment.minsalary = minsalary
    interviewcomment.maxsalary = maxsalary
    interviewcomment.minemploydate = minemploydate
    interviewcomment.maxemploydate = maxemploydate
    interviewcomment.posterid = posterid
    interviewcomment.isagree=isagree
    interviewcomment.created_time=interviewcomment.updated_time=getCurrentTime()

    db.session.add(interviewcomment)
    db.session.commit()


    user=User.query.filter_by(id=interviewid).first()
    user.salary=salary
    if employdate != '':
        user.employdate=employdate
    db.session.add(user)
    db.session.commit()

    msg = {
        "msgtype": "text",
        "text": {
            "content": "面试官【" + username + "】已提交关于面试人【" + interviewname + "】的面试意见，请进入人事系统进行后续操作"
        }
    }
    dingtalksn = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=posterlist)

    return json.dumps("评价成功", ensure_ascii=False)




@interview_page.route('/getinterviewerbydate', methods=['GET', 'POST'])
def getinterviewbydate():
    user = User.query.filter_by(status=2).all()
    # 取面试时间
    date=[]
    for i in user :
        tempdate=str(i.interviewdate)[0:10]
        date.append(tempdate)

    # 去重
    searchdate=list(set(date))

    # 根据面试时间找人
    finaldata = []
    for k in searchdate:
        tempuser=User.query.filter_by(status=2).filter(db.cast(User.interviewdate, db.DATE) == k).all()
        content = []
        for l in tempuser:
            temp = dict(name=str(l))
            content.append(temp)
        temp2 = dict(datadate=k,content=content)
        finaldata.append(temp2)

    return json.dumps(finaldata, ensure_ascii=False)

@interview_page.route('/getinterviewerdetail', methods=['GET', 'POST'])
def getinterviewerdetail():
    interviewdate = request.json.get("interviewdate")
    # interviewdate="2022-07-12"
    user = User.query.filter(db.cast(User.interviewdate, db.DATE) == interviewdate).all()
    rts=[]
    for item in user:
        temp = dict(id=item.id, name=item.name, department=item.department.name, phone=item.mobile, date=str(item.interviewdate))
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@interview_page.route('/getgoal', methods=['GET', 'POST'])
def getgoal():
    goal=InterviewGoal.query.all()
    rts=[]
    for item in goal:
        temp = dict(id=item.id, sn=item.sn, department=item.department.name, post=item.post,
                    num=item.num)
        rts.append(temp)

    return json.dumps(rts, ensure_ascii=False)



@interview_page.route('/sendoffer', methods=['GET', 'POST'])
def sendoffer():
    id=request.form.get("id")
    mailaddress=request.form.get("email")
    offertype = request.form.get("offertype")
    depid=request.form.get("depid")
    post=request.form.get("post")
    employdate=request.form.get("employdate")

    f = request.files.getlist('files')

    user=User.query.filter_by(id=id).first()
    name=user.name
    mobile=user.mobile

    theme=offertype+"录用通知书"
    content=""

    depname = "人力资源部"

    time = dateafter(5)
    nowtime=dateafter(0)
    url = 'http://101.132.227.54:88/interviewenter?id=' + id+'&mobile='+mobile

    msg = Message(theme, sender='lijia@omhgroup.com', recipients=[mailaddress], body=content)  # 使用Messgae方法
    msg.html = ops_render("/mail/offer.html",{'nowtime':nowtime,'name':name,"time":time,"company":offertype,"url":url,"depname":depname})
    msg.attach("入职通知书.pdf", 'application/pdf', f[0].read())
    mail.send(msg)  # 使用Mail类中的send()方法

    user.status = 3
    user.depid=depid
    user.post=post
    user.employdate=employdate
    db.session.commit()

    return json.dumps('邮件发送成功', ensure_ascii=False)



@interview_page.route('/enterdingtalk', methods=['GET', 'POST'])
def enterdingtalk():
    id=request.json.get('id')
    mobile=request.json.get('mobile')
    user=User.query.filter_by(id=id).first()
    userinfo = {"name": user.name, "mobile":mobile, "userid": id,"dept_id_list":"699351474","job_number":id}
    url = 'https://oapi.dingtalk.com/topapi/v2/user/create'
    res = dingtalkpost(url, userinfo)
    if res['errcode'] ==40103:
        rts={"msg":"邀请已发送，请进入钉钉查看","isdone":True}
    else:
        rts={"msg":res['errmsg'],"isdone":False}

    return json.dumps(rts, ensure_ascii=False)


@interview_page.route('/deleteinterview', methods=['GET', 'POST'])
def deleteinterview():
    id = request.json.get('id')
    interview = User.query.filter_by(id=id).delete()
    db.session.commit()
    return json.dumps({"msg": "人员简历已删除"}, ensure_ascii=False)
